package com.scut.campus.interceptor;

import com.scut.campus.context.BaseContext;
import com.scut.campus.entity.base.BaseDO;
import com.scut.campus.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.util.Properties;

@Intercepts({
        @Signature(
                type = Executor.class,
                method = "update",
                args = {MappedStatement.class, Object.class}
        )
})
@Slf4j
public class AutoFillPlugin implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] parameters = invocation.getArgs();

        for (Object parameter : parameters) {
            // 检查参数是否是 BaseDO 的子类
            if (!(parameter instanceof BaseDO)) {
                continue;
            }
            BaseDO baseDO = (BaseDO) parameter;


            // 获取MappedStatement对象
            MappedStatement mappedStatement = (MappedStatement) parameters[0];
            // 获取SQL命令类型
            SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

            // 根据不同类型执行不同逻辑
            switch (sqlCommandType) {
                case INSERT:
                    insertSingleBaseDO(baseDO);
                case UPDATE:
                    updateSingleBaseDO(baseDO);
                default:
                    log.info("自动填充找到意外的SQL命令类型：{}", sqlCommandType);
            }
        }
        return invocation.proceed();
    }

    public void updateSingleBaseDO(BaseDO baseDO) {
        baseDO.setUpdateTimestamp(DateTimeUtil.getTimestamp10());
        baseDO.setUpdateUserId(String.valueOf(BaseContext.getCurrentId()));
        baseDO.setVersion(1L);
    }

    public void insertSingleBaseDO(BaseDO baseDO) {
        baseDO.setCreateTimestamp(DateTimeUtil.getTimestamp10());
        baseDO.setUpdateTimestamp(DateTimeUtil.getTimestamp10());
        baseDO.setCreateUserId(String.valueOf(BaseContext.getCurrentId()));
        baseDO.setUpdateUserId(String.valueOf(BaseContext.getCurrentId()));
        baseDO.setVersion(1L);
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以在这里设置插件的属性
    }
}
